<template>
  <a-upload :action="uploadUrl" 
    :multiple="remainingNumber > 1" 
    :fileList="fileList" 
    :beforeUpload="handleBeforeUpload" 
    @change="handleChange">
    <a-button :disabled="fileList.length >= option.maxNumber">
      <a-icon type="upload"/> 上传文件
    </a-button>
    <span class="ml-1 text-secondary number-limit">
      数量限制：{{option.minNumber}}<span v-if="option.maxNumber > option.minNumber">~{{option.maxNumber}}</span>
    </span>
  </a-upload>
</template>

<script>
import consts from '../../consts'
export default {
  name: 'File',
  props: {
    fieldId: {
      type: String,
      requried: true
    },
    option: {
      type: Object,
      requried: false,
      default: () => {
        return {
          maxNumber: 1,
          minNumber: 1
        };
      }
    },
    defaultHelp: {
      type: String,
      required: false,
      default: () => {
        return '';
      }
    }
  },
  computed: {
    remainingNumber() {
      return this.option.maxNumber - this.fileList.length;
    }
  },
  data() {
    return {
      uploadUrl: consts.uploadUrl,
      fileList: []
    };
  },
  methods: {
    handleBeforeUpload(file, fileList) {
      const remainingNumber = this.option.maxNumber - this.fileList.length;
      const size = fileList.length + this.fileList.length;
      if (size > this.option.maxNumber) {
        const removeSize = size - this.option.maxNumber;
        fileList.splice(this.option.maxLength - removeSize, removeSize);
      }
    },
    handleChange({fileList}) {
      this.fileList = fileList;
      if (fileList.length < this.option.minNumber && fileList.length > 0) {
        this.$store.dispatch('validate', {fieldId: self.fieldId, status: 'error', help: '上传到的文件数量不能少于' + this.option.minNumber});
      } else {
        this.$store.dispatch('validate', {fieldId: self.fieldId, status: undefined, help: this.defaultHelp});
        this.$emit('change', fileList);
      }
    }
  }
}
</script>

<style scoped>
.number-limit {
  cursor: pointer;
  margin-right: 32px;
}
</style>